package com.lzb.watermarkcamera.activity;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.FragmentTransaction;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzb.watermarkcamera.AppConfig;
import com.lzb.watermarkcamera.BaseAc;
import com.lzb.watermarkcamera.BaseEditFragment;
import com.lzb.watermarkcamera.Content;
import com.lzb.watermarkcamera.HomeActivity;
import com.lzb.watermarkcamera.R;
import com.lzb.watermarkcamera.basic.imgedit.CropImageView;
import com.lzb.watermarkcamera.basic.imgedit.ImageViewTouch;
import com.lzb.watermarkcamera.basic.imgedit.ImageViewTouchBase;
import com.lzb.watermarkcamera.basic.imgedit.TextStickerView;
import com.lzb.watermarkcamera.basic.utils.FileUtil;
import com.lzb.watermarkcamera.basic.utils.RxUtil;
import com.lzb.watermarkcamera.basic.utils.SPUtil;
import com.lzb.watermarkcamera.bean.Hours24Bean;
import com.lzb.watermarkcamera.bean.PersonalCardBean;
import com.lzb.watermarkcamera.bean.WatermarkBean;
import com.lzb.watermarkcamera.databinding.ActivityPicEditBinding;
import com.lzb.watermarkcamera.dialog.DeleteDialog;
import com.lzb.watermarkcamera.dialog.WatermarkTemplateDialog;
import com.lzb.watermarkcamera.fragment.AddTextFragment;
import com.lzb.watermarkcamera.fragment.CropFragment;
import com.lzb.watermarkcamera.fragment.PaintFragment;
import com.lzb.watermarkcamera.utils.AppSpUtils;
import com.lzb.watermarkcamera.utils.CityUtils;
import com.lzb.watermarkcamera.utils.MyMediaRecorder;
import com.lzb.watermarkcamera.utils.OkhttpUtils;
import com.lzb.watermarkcamera.view.RoundedLinearLayout;
import com.vilyever.drawingview.DrawingView;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import io.reactivex.rxjava3.core.ObservableEmitter;

public class PicEditActivity extends BaseAc<ActivityPicEditBinding> implements View.OnClickListener, SensorEventListener {

    public static final int MODE_NONE = 0;
    public static final int MODE_TEXT = 5;// 文字模式
    public static final int MODE_PAINT = 6;//画笔模式
    public static final int MODE_CROP = 3;// 剪裁模式

    public static String sImgPath;
    private Bitmap mRetBitmap;
    public int mode = MODE_NONE;// 当前操作模式

    public ImageViewTouch mImgView;
    public CropImageView mCropView;
    public DrawingView mPaintView;
    public TextStickerView mTextStickerView;

    private AddTextFragment mAddTextFragment;
    private PaintFragment mPaintFragment;
    private CropFragment mCropFragment;


    //水印相关
    private int selPosition;
    private View view;
    private SensorManager sensorManager;
    private long lastUpdateTime = 0;
    private boolean hasRecord = false;
    private boolean isAddWatermark = false;
    private MyMediaRecorder mRecorder;
    private Handler mHandler;
    float volume = 10000;
    private WatermarkTemplateDialog watermarkTemplateDialog;

    private final Runnable mTaskUpdateTime = new Runnable() {
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void run() {
            if (!hasRecord || !isAddWatermark) return;
            if (selPosition != 0) return;
            volume = mRecorder.getMaxAmplitude();  //获取声压值
            if (volume > 0 && volume < 1000000) {
                float value = 20 * (float) (Math.log10(volume));
                int val = (int) value;
                TextView tvDecibel = view.findViewById(R.id.tvDecibel);
                if (val < 30) {
                    tvDecibel.setText(getString(R.string.decibel) + "：" + val + getString(R.string.decibel_text1));
                } else if (val < 60) {
                    tvDecibel.setText(getString(R.string.decibel) + "：" + val + getString(R.string.decibel_text2));
                } else if (val < 90) {
                    tvDecibel.setText(getString(R.string.decibel) + "：" + val + getString(R.string.decibel_text3));
                } else {
                    tvDecibel.setText(getString(R.string.decibel) + "：" + val + getString(R.string.decibel_text4));
                }
            }
            mHandler.postDelayed(this, 1000);
        }
    };

    @Override
    public void onBackPressed() {
        switch (mode) {
            case MODE_TEXT:
                mAddTextFragment.backToMain();
                return;
            case MODE_PAINT:
                mPaintFragment.backToMain();
                return;
            case MODE_CROP:
                mCropFragment.backToMain();
                return;
            default:
                break;
        }
        super.onBackPressed();
    }

    @Override
    protected boolean isStatusBarTextDark() {
        return false;
    }

    @Override
    protected int onCreate() {
        return R.layout.activity_pic_edit;
    }

    @Override
    protected void initView() {
        mDataBinding.ivPicEditBack.setOnClickListener(view -> onBackPressed());

        mDataBinding.tvSave.setOnClickListener(this);
        mDataBinding.tvCompelete.setOnClickListener(this);
        mDataBinding.tvAddWatermark.setOnClickListener(this);
        mDataBinding.tvAddText.setOnClickListener(this);
        mDataBinding.tvAddAnnotation.setOnClickListener(this);
        mDataBinding.tvCrop.setOnClickListener(this);
        mDataBinding.tvDelete.setOnClickListener(this);

        mImgView = mDataBinding.imageViewTouch;
        mTextStickerView = mDataBinding.txtStickerView;
        mPaintView = mDataBinding.myDrawingView;
        mCropView = mDataBinding.cropImgView;

        mHandler = new Handler();

        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        //加速度感应器
        Sensor magneticSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        //地磁感应器
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(this, magneticSensor, SensorManager.SENSOR_DELAY_GAME);
        sensorManager.registerListener(this, accelerometerSensor, SensorManager.SENSOR_DELAY_GAME);

        mRecorder = new MyMediaRecorder();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tvSave) {//保存
            saveImg();
        } else if (id == R.id.tvCompelete) {//完成
            clickApply();
        } else if (id == R.id.tvAddWatermark) {//添加水印
            showWatermarkTemplateDialog();
        } else if (id == R.id.tvAddText) {//加文字
            showFragmentByFunc(MODE_TEXT);
        } else if (id == R.id.tvAddAnnotation) {//加批注
            showFragmentByFunc(MODE_PAINT);
        } else if (id == R.id.tvCrop) {//裁剪
            showFragmentByFunc(MODE_CROP);
        } else if (id == R.id.tvDelete) {//删除
            showDeleteDialog();
        }
    }

    @Override
    protected void initData() {
        if (sImgPath != null && !sImgPath.isEmpty()) {
            mRetBitmap = ImageUtils.getBitmap(sImgPath);
        }
        mDataBinding.imageViewTouch.setImageBitmap(mRetBitmap);
        mDataBinding.imageViewTouch.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);

        boolean hasRecordAudioPermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.RECORD_AUDIO)
                == PackageManager.PERMISSION_GRANTED;
        if (hasRecordAudioPermission && !hasRecord) {
            startTest();
        }
    }

    //保存图片
    private void saveImg() {
        showDialog(getString(R.string.save_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        Bitmap bitmap = ImageUtils.view2Bitmap(mDataBinding.rlSave);
                        ImageUtils.save2Album(bitmap, Bitmap.CompressFormat.PNG);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.save_suc));
                        finish();
                    }
                });
            }
        }, 1000);
    }

    private void showFragmentByFunc(int mode) {
        showEdit();
        switch (mode) {
            case AddTextFragment.INDEX:
                showAddTextFragment();
                break;
            case PaintFragment.INDEX:
                showPaintFragment();
                break;
            case CropFragment.INDEX:
                showCropFragment();
                break;
            default:
                break;
        }
    }

    /**
     * 点击右下角“勾”后的处理
     */
    private void clickApply() {
        switch (mode) {
            case MODE_TEXT:
                mAddTextFragment.applyTextImage();
                break;
            case MODE_PAINT:
                mPaintFragment.applyPaintImage();
                break;
            case MODE_CROP:
                mCropFragment.applyCropImage();
                return;
            default:
                break;
        }
    }

    private void showAddTextFragment() {
        if (mAddTextFragment == null) {
            mAddTextFragment = AddTextFragment.newInstance();
        } else {
            mAddTextFragment.onShow();
        }
        showFragment(mAddTextFragment);
    }

    private void showPaintFragment() {
        if (mPaintFragment == null) {
            mPaintFragment = PaintFragment.newInstance();
        } else {
            mPaintFragment.onShow();
        }
        showFragment(mPaintFragment);
    }

    private void showCropFragment() {
        if (mCropFragment == null) {
            mCropFragment = CropFragment.newInstance();
        } else {
            mCropFragment.onShow();
        }
        showFragment(mCropFragment);
    }

    private void showFragment(BaseEditFragment baseEditFragment) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.flFragmentContainer, baseEditFragment);
        fragmentTransaction.commitAllowingStateLoss();
    }

    public Bitmap getMainBit() {
        return mRetBitmap;
    }

    public void changeMainBitmap(Bitmap newBit, boolean needPushUndoStack) {
        if (newBit == null) {
            return;
        }

        if (mRetBitmap != newBit) {
            mRetBitmap = newBit;
            mImgView.setImageBitmap(mRetBitmap);
            mImgView.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
        }
    }

    private void showEdit() {
        mDataBinding.tvSave.setVisibility(View.GONE);
        mDataBinding.tvCompelete.setVisibility(View.VISIBLE);
        mDataBinding.llPicEditBottom.setVisibility(View.GONE);
        mDataBinding.flFragmentContainer.setVisibility(View.VISIBLE);
    }

    public void showFunc() {
        mDataBinding.tvSave.setVisibility(View.VISIBLE);
        mDataBinding.tvCompelete.setVisibility(View.GONE);
        mDataBinding.llPicEditBottom.setVisibility(View.VISIBLE);
        mDataBinding.flFragmentContainer.setVisibility(View.INVISIBLE);
    }

    private void showDeleteDialog() {
        DeleteDialog dialog = new DeleteDialog(mContext);
        dialog.setListener(new DeleteDialog.Ilistener() {
            @Override
            public void clickDelete() {
                String filePath = FileUtil.generateFilePath(Content.recentDelete, "." + FileUtils.getFileExtension(sImgPath));
                FileUtils.copy(sImgPath, filePath);
                FileUtils.delete(sImgPath);
                finish();
            }
        });
        dialog.show();
    }


    private void setWatermarkData() {
        mDataBinding.llWatermark.removeAllViews();

        WatermarkBean watermarkBean = AppSpUtils.getWatermarkList().get(selPosition);

        if (selPosition == 0) {
            view = LayoutInflater.from(this).inflate(R.layout.layout_custom_watermark, null, false);

            LinearLayout llCard = view.findViewById(R.id.llCard);
            ImageView ivCardImg = view.findViewById(R.id.ivCardImg);
            TextView tvCardName = view.findViewById(R.id.tvCardName);
            TextView tvCardPhone = view.findViewById(R.id.tvCardPhone);
            ImageView ivLogo = view.findViewById(R.id.ivLogo);
            TextView tvCustomText = view.findViewById(R.id.tvCustomText);
            TextView tvNumber = view.findViewById(R.id.tvNumber);
            TextView tvCount = view.findViewById(R.id.tvCount);
            TextView tvTime = view.findViewById(R.id.tvTime);
            TextView tvWeather = view.findViewById(R.id.tvWeather);
            TextView tvLocation = view.findViewById(R.id.tvLocation);
            TextView tvElevation = view.findViewById(R.id.tvElevation);
            TextView tvAzimuth = view.findViewById(R.id.tvAzimuth);
            TextView tvSpeed = view.findViewById(R.id.tvSpeed);
            TextView tvLongitudeAndLatitude = view.findViewById(R.id.tvLongitudeAndLatitude);
            TextView tvDecibel = view.findViewById(R.id.tvDecibel);
            TextView tvPhotographer = view.findViewById(R.id.tvPhotographer);
            TextView tvCustomContent = view.findViewById(R.id.tvCustomContent);
            TextView tvWatermarkVerification = view.findViewById(R.id.tvWatermarkVerification);

            WatermarkBean.CustomBean customBean = watermarkBean.getCustomBean();

            // 水印验证
            if (customBean.isOpenWaterVerification()) {
                tvWatermarkVerification.setVisibility(View.VISIBLE);
            } else {
                tvWatermarkVerification.setVisibility(View.GONE);
            }

            // Logo
            if (customBean.isOpenLogo()) {
                Glide.with(this).load(customBean.getLogoPath()).into(ivLogo);
                ivLogo.setVisibility(View.VISIBLE);
            } else {
                ivLogo.setVisibility(View.GONE);
            }

            // 个人名片
            if (customBean.isOpenPersonalCard()) {
                llCard.setVisibility(View.VISIBLE);
                PersonalCardBean personalCardBean = AppSpUtils.getPersonalCard();
                Glide.with(this).load(personalCardBean.getImgPath()).into(ivCardImg);
                tvCardName.setText(personalCardBean.getName());
                tvCardPhone.setText(personalCardBean.getPhoneNumber());
            } else {
                llCard.setVisibility(View.GONE);
            }

            // 自定义文字
            if (customBean.isOpenCustomText()) {
                tvCustomText.setVisibility(View.VISIBLE);
                tvCustomText.setText(customBean.getText());
            } else {
                tvCustomText.setVisibility(View.GONE);
            }

            // 编号
            if (customBean.isOpenNumber()) {
                tvNumber.setVisibility(View.VISIBLE);
                String number = customBean.getNumber();
                if (TextUtils.isEmpty(number)) {
                    long mills = TimeUtils.getNowMills() / 1000;
                    String millsStr = String.valueOf(mills);
                    if (millsStr.length() == 10) {
                        String part1 = millsStr.substring(0, 3);
                        String part2 = millsStr.substring(3, 6);
                        String part3 = millsStr.substring(6, 10);
                        String formattedNumber = part1 + "-" + part2 + "-" + part3;
                        tvNumber.setText(getString(R.string.number) + "：" + formattedNumber);
                    }
                } else {
                    tvNumber.setText(getString(R.string.number) + "：" + number);
                }
            } else {
                tvNumber.setVisibility(View.GONE);
            }

            // 计数
            if (customBean.isOpenCount()) {
                tvCount.setVisibility(View.VISIBLE);
                tvCount.setText(getString(R.string.count) + "：" + SPUtil.getLong(this, Content.count, 1L));
            } else {
                tvCount.setVisibility(View.GONE);
            }

            // 时间
            if (customBean.isOpenTime()) {
                tvTime.setVisibility(View.VISIBLE);
                tvTime.setText(getString(R.string.time) + "：" + AppConfig.DATE + " " + AppConfig.TIME);
            } else {
                tvTime.setVisibility(View.GONE);
            }

            // 天气
            if (customBean.isOpenWeather()) {
                tvWeather.setVisibility(View.VISIBLE);
            } else {
                tvWeather.setVisibility(View.GONE);
            }

            // 位置
            if (customBean.isOpenLocation()) {
                tvLocation.setVisibility(View.VISIBLE);
            } else {
                tvLocation.setVisibility(View.GONE);
            }

            // 海拔
            if (customBean.isOpenElevation()) {
                tvElevation.setVisibility(View.VISIBLE);
            } else {
                tvElevation.setVisibility(View.GONE);
            }

            // 方位
            if (customBean.isOpenAzimuth()) {
                tvAzimuth.setVisibility(View.VISIBLE);
                tvAzimuth.setText(getString(R.string.azimuth) + "：0°");
            } else {
                tvAzimuth.setVisibility(View.GONE);
            }

            // 速度
            if (customBean.isOpenSpeed()) {
                tvSpeed.setVisibility(View.VISIBLE);
            } else {
                tvSpeed.setVisibility(View.GONE);
            }

            // 经纬度
            if (customBean.isOpenLongitudeAndLatitude()) {
                tvLongitudeAndLatitude.setVisibility(View.VISIBLE);
            } else {
                tvLongitudeAndLatitude.setVisibility(View.GONE);
            }

            // 分贝
            if (customBean.isOpenDecibel()) {
                tvDecibel.setVisibility(View.VISIBLE);
            } else {
                tvDecibel.setVisibility(View.GONE);
            }

            // 摄影师
            if (customBean.isOpenPhotographer()) {
                tvPhotographer.setVisibility(View.VISIBLE);
                WatermarkBean.PhotographerBean photographerBean = customBean.getPhotographerBean();
                if (photographerBean != null) {
                    tvPhotographer.setText(photographerBean.getTitle() + "：" + photographerBean.getContent());
                } else {
                    tvPhotographer.setText(getString(R.string.photographer) + "：" + getString(R.string.click_edit));
                }
            } else {
                tvPhotographer.setVisibility(View.GONE);
            }

            // 自定义内容列表
            List<String> listContent = customBean.getCustomTextList();
            if (listContent != null && !listContent.isEmpty()) {
                tvCustomContent.setVisibility(View.VISIBLE);
                String content = "";
                for (int i = 0; i < listContent.size(); i++) {
                    content += listContent.get(i);
                    if (i != listContent.size() - 1) {
                        content += '\n';
                    }
                }
                tvCustomContent.setText(content);
            } else {
                tvCustomContent.setVisibility(View.GONE);
            }

            boolean hasPermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED;
            if (!hasPermission) {
                tvWeather.setText(getString(R.string.weather) + "：" + getString(R.string.not_award_permission));
                tvLocation.setText(getString(R.string.location) + "：" + getString(R.string.not_award_permission));
                tvElevation.setText(getString(R.string.elevation) + "：" + getString(R.string.not_award_permission));
                tvSpeed.setText(getString(R.string.speed) + "：" + getString(R.string.not_award_permission));
                tvLongitudeAndLatitude.setText(getString(R.string.longitude_and_latitude) + "：" + getString(R.string.not_award_permission));
            } else {
                initLocation();
            }

        } else {
            // Common 水印模板 (position 1-7)
            WatermarkBean.CommonBean commonBean = watermarkBean.getCommonBean();

            if (selPosition == 1) {
                view = LayoutInflater.from(this).inflate(R.layout.layout_common_watermark1, null, false);

                TextView tvTheme = view.findViewById(R.id.tvTheme);
                TextView tvPeople = view.findViewById(R.id.tvPeople);

                tvTheme.setText(commonBean.getTheme());
                if (commonBean.getPeople() != null) {
                    tvPeople.setText(getString(R.string.inspector) + "：" + commonBean.getPeople());
                } else {
                    tvPeople.setText(getString(R.string.inspector) + "：" + getString(R.string.click_edit_content));
                }

            } else if (selPosition == 2) {
                view = LayoutInflater.from(this).inflate(R.layout.layout_common_watermark2, null, false);

                TextView tvTheme = view.findViewById(R.id.tvTheme);
                tvTheme.setText(commonBean.getTheme());

            } else if (selPosition == 3 || selPosition == 4 || selPosition == 5) {
                if (selPosition == 3) {
                    view = LayoutInflater.from(this).inflate(R.layout.layout_common_watermark3, null, false);
                } else if (selPosition == 4) {
                    view = LayoutInflater.from(this).inflate(R.layout.layout_common_watermark4, null, false);
                } else {
                    view = LayoutInflater.from(this).inflate(R.layout.layout_common_watermark5, null, false);
                }

                TextView tvTheme = view.findViewById(R.id.tvTheme);
                tvTheme.setText(commonBean.getTheme());

            } else if (selPosition == 6) {
                view = LayoutInflater.from(this).inflate(R.layout.layout_common_watermark6, null, false);

            } else if (selPosition == 7) {
                view = LayoutInflater.from(this).inflate(R.layout.layout_common_watermark7, null, false);
            }

            // 设置公共的日期、时间、星期、位置信息
            TextView tvDate = view.findViewById(R.id.tvDate);
            TextView tvTime = view.findViewById(R.id.tvTime);
            TextView tvWeek = view.findViewById(R.id.tvWeek);
            TextView tvLocation = view.findViewById(R.id.tvLocation);

            tvDate.setText(AppConfig.DATE);
            tvTime.setText(AppConfig.TIME);
            long mill = TimeUtils.string2Millis(AppConfig.DATE, new SimpleDateFormat("yyyy-MM-dd"));
            tvWeek.setText(TimeUtils.millis2String(mill, new SimpleDateFormat("EEEE")));
            if (commonBean.getLocation() != null) {
                if (selPosition == 1) {
                    tvLocation.setText(getString(R.string.inspection_location) + "：" + commonBean.getLocation());
                } else {
                    tvLocation.setText(commonBean.getLocation());
                }
            } else {
                if (selPosition == 1) {
                    tvLocation.setText(getString(R.string.inspection_location) + "：" + getString(R.string.click_edit_content));
                } else {
                    tvLocation.setText(getString(R.string.click_edit_content));
                }
            }

            // 设置水印背景颜色（仅适用于非第6、7位置的水印模板）
            if (selPosition != 6 && selPosition != 7) {
                RoundedLinearLayout llWatermarkBg = view.findViewById(R.id.llWatermarkBg);
                if (llWatermarkBg != null) {
                    llWatermarkBg.setBackgroundColor(Color.parseColor(commonBean.getThemeColor()));
                }
            }
        }

        // 设置llWatermark的宽度与当前加载的布局文件实际宽度一致
        ViewGroup.LayoutParams watermarkParams = mDataBinding.llWatermark.getLayoutParams();

        // 根据选择的position设置对应的布局宽度，默认为match_parent
        switch (selPosition) {
            case 1:
                watermarkParams.width = (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 229, getResources().getDisplayMetrics()
                ); // layout_common_watermark1: 229dp
                break;
            case 2:
                watermarkParams.width = (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 230, getResources().getDisplayMetrics()
                ); // layout_common_watermark2: 230dp
                break;
            case 3:
            case 4:
            case 5:
                watermarkParams.width = (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 240, getResources().getDisplayMetrics()
                ); // layout_common_watermark3/4/5: 240dp
                break;
            case 6:
                watermarkParams.width = (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 240, getResources().getDisplayMetrics()
                ); // layout_common_watermark6: 240dp
                break;
            case 7:
                watermarkParams.width = (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 240, getResources().getDisplayMetrics()
                ); // layout_common_watermark7: 240dp
                break;
            default:
                watermarkParams.width = ViewGroup.LayoutParams.MATCH_PARENT; // 默认match_parent
                break;
        }

        mDataBinding.llWatermark.setLayoutParams(watermarkParams);

        // 将水印视图添加到主布局
        mDataBinding.llWatermark.addView(view);
    }

    private void showWatermarkTemplateDialog() {
        if (watermarkTemplateDialog == null){
            watermarkTemplateDialog = new WatermarkTemplateDialog(mContext);
            watermarkTemplateDialog.setSelPosition(-1);
        }
        watermarkTemplateDialog.setListener(new WatermarkTemplateDialog.Ilistener() {
            @Override
            public void clickItem(int pos) {
                selPosition = pos;
                setWatermarkData();
                isAddWatermark = true;
            }
        });
        watermarkTemplateDialog.show();
    }

    private LocationManager mLocationMgr; // 声明一个定位管理器对象


    private boolean isLocationEnable = false; // 定位服务是否可用

    public void initLocation() {
        mLocationMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria(); // 创建一个定位准则对象
        criteria.setAccuracy(Criteria.ACCURACY_FINE); // 设置定位精确度
        criteria.setAltitudeRequired(true); // 设置是否需要海拔信息
        criteria.setBearingRequired(true); // 设置是否需要方位信息
        criteria.setCostAllowed(true); // 设置是否允许运营商收费
        criteria.setPowerRequirement(Criteria.POWER_LOW); // 设置对电源的需求
        // 获取定位管理器的最佳定位提供者
        String bestProvider = mLocationMgr.getBestProvider(criteria, true);
        if (bestProvider != null && mLocationMgr.isProviderEnabled(bestProvider)) { // 定位提供者当前可用
            beginLocation(bestProvider); // 开始定位
            isLocationEnable = true;
        } else { // 定位提供者暂不可用
            ToastUtils.showShort(getString(R.string.please_open_location_service));
            isLocationEnable = false;
        }
    }

    private void beginLocation(String method) {

        // 检查当前设备是否已经开启了定位功能

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)

                != PackageManager.PERMISSION_GRANTED) {
            ToastUtils.showShort(getString(R.string.please_open_location_permission));
            return;

        }

        // 设置定位管理器的位置变更监听器

        mLocationMgr.requestLocationUpdates(method, 300, 0, mLocationListener);

        // 获取最后一次成功定位的位置信息

        Location location = mLocationMgr.getLastKnownLocation(method);
        if (location != null) {
            setLocation(location); // 显示定位结果文本
        }


    }
    // 定义一个位置变更监听器

    private LocationListener mLocationListener = new LocationListener() {

        @Override

        public void onLocationChanged(Location location) {
            if (location != null) {
                setLocation(location); // 显示定位结果文本
            }
        }

        @Override

        public void onProviderDisabled(String arg0) {
        }

        @Override

        public void onProviderEnabled(String arg0) {
        }

        @Override

        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        }

    };

    private void setLocation(Location location) {
        if (selPosition != 0) return;

        double latitude = location.getLatitude();
        double longitude = location.getLongitude();

        // 创建DecimalFormat实例用于格式化数值
        DecimalFormat df = new DecimalFormat("#.##");

        // 获取并显示位置名称
        String locationStr = getLocationName(latitude, longitude);
        if (!TextUtils.isEmpty(locationStr)) {
            mLocationMgr.removeUpdates(mLocationListener);
        }

        TextView tvElevation = view.findViewById(R.id.tvElevation);
        TextView tvSpeed = view.findViewById(R.id.tvSpeed);
        TextView tvLongitudeAndLatitude = view.findViewById(R.id.tvLongitudeAndLatitude);

        // 显示海拔信息
        if (location.hasAltitude()) {
            double altitude = location.getAltitude();
            String altitudeStr = df.format(altitude) + "米";
            tvElevation.setText(getString(R.string.elevation) + "：" + altitudeStr);
        } else {
            String altitudeStr = "0.0米";
            tvElevation.setText(getString(R.string.elevation) + "：" + altitudeStr);
        }

        // 显示速度信息
        if (location.hasSpeed()) {
            float speed = location.getSpeed();
            int speedInt = (int) Math.round(speed * 3.6); // 转换为km/h并四舍五入为整数
            String speedStr = speedInt + " 公里/小时";
            tvSpeed.setText(getString(R.string.speed) + "：" + speedStr);
        } else {
            String speedStr = "0公里/小时";
            tvSpeed.setText(getString(R.string.speed) + "：" + speedStr);
        }

        // 显示经纬度信息
        String latStr = df.format(Math.abs(latitude)) + "°" + (latitude >= 0 ? "N" : "S");
        String lonStr = df.format(Math.abs(longitude)) + "°" + (longitude >= 0 ? "E" : "W");
        String latLonStr = latStr + ", " + lonStr;
        tvLongitudeAndLatitude.setText(getString(R.string.longitude_and_latitude) + "：" + latLonStr);
    }

    private String getLocationName(double lat, double lon) {

        TextView tvLocation = view.findViewById(R.id.tvLocation);
        // 创建DecimalFormat实例用于格式化经纬度
        DecimalFormat df = new DecimalFormat("#.#####");

        // 方案1：使用Android原生Geocoder
        if (Geocoder.isPresent()) {
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            try {
                List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);
                if (!addresses.isEmpty()) {
                    Address address = addresses.get(0);
                    String location = address.getAddressLine(address.getMaxAddressLineIndex());
                    tvLocation.setText(getString(R.string.location) + "：" + location);
                    getCity24(CityUtils.getCityId(addresses.get(0).getLocality()));
                    return location;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 如果Geocoder不可用，只显示格式化的经纬度
        String latStr = df.format(Math.abs(lat)) + "°" + (lat >= 0 ? "N" : "S");
        String lonStr = df.format(Math.abs(lon)) + "°" + (lon >= 0 ? "E" : "W");
        String coordsOnly = latStr + ", " + lonStr;
        tvLocation.setText(getString(R.string.location) + "：" + coordsOnly);
        return "";
    }

    private void getCity24(String cityId) {
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("cityId", cityId);
        /*   stringStringHashMap.put("token", "008d2ad9197090c5dddc76f583616606");*/
        OkhttpUtils.getInstance().postRequest("whapi/json/alicityweather/forecast24hours", stringStringHashMap, new OkhttpUtils.HttpCallBack() {
            @Override
            public void onSusscess(String data) {
                Hours24Bean cityInfoBean = new Gson().fromJson(data, Hours24Bean.class);
                if (cityInfoBean.getCode() == 0) {
                    List<Hours24Bean.DataBean.HourlyBean> hourList = cityInfoBean.getData().getHourly();
                    if (!hourList.isEmpty()) {
                        //当前气温
                        int temp = (int) hourList.get(0).getTemp();

                        TextView tvWeather = view.findViewById(R.id.tvWeather);

                        tvWeather.setText(hourList.get(0).getCondition() + " " + temp + "℃");
                    }
                }

            }

            @Override
            public void onFail(String meg) {
                Log.e("sssssss", meg);
            }
        });
    }

    float[] accelerometerValues = new float[3];

    float[] magneticValues = new float[3];

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (selPosition != 0 || !isAddWatermark) return;
        // 判断当前是加速度感应器还是地磁感应器
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            //赋值调用clone方法
            accelerometerValues = event.values.clone();
        } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
            //赋值调用clone方法
            magneticValues = event.values.clone();
        }
        if (accelerometerValues != null && magneticValues != null) {
            long curTime = System.currentTimeMillis();
            if (curTime - lastUpdateTime < 500) return;
            lastUpdateTime = curTime;
            calculateOrientation(); // 加速度和磁场强度两个都有了，才能计算磁极的方向
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    //计算方位
    private void calculateOrientation() {
        float[] R = new float[9];
        float[] values = new float[3];
        SensorManager.getRotationMatrix(R, null, accelerometerValues, magneticValues);
        sensorManager.getOrientation(R, values);
        //values[0]的取值范围是-180到180度。
        double value = Math.toDegrees(values[0]);
        //+-180表示正南方向，0度表示正北，-90表示正西，+90表示正东

        // 将value转换为0-360度范围
        if (value < 0) {
            value = value + 360;
        }

        String direction = "";
        if ((value >= 337.5 && value <= 360) || (value >= 0 && value < 22.5)) {
            direction = "北";
        } else if (value >= 22.5 && value < 67.5) {
            direction = "东北";
        } else if (value >= 67.5 && value < 112.5) {
            direction = "东";
        } else if (value >= 112.5 && value < 157.5) {
            direction = "东南";
        } else if (value >= 157.5 && value < 202.5) {
            direction = "南";
        } else if (value >= 202.5 && value < 247.5) {
            direction = "西南";
        } else if (value >= 247.5 && value < 292.5) {
            direction = "西";
        } else if (value >= 292.5 && value < 337.5) {
            direction = "西北";
        }

        TextView tvAzimuth = view.findViewById(com.lzb.watermarkcamera.R.id.tvAzimuth);

        // 更新UI显示方位角
        DecimalFormat df = new DecimalFormat("0");
        String azimuthText = getString(com.lzb.watermarkcamera.R.string.azimuth) + "：" + direction + " " + df.format(value) + "° ";
        tvAzimuth.setText(azimuthText);
    }

    //开始检测
    private void startTest() {
        String musicPath = FileUtil.generateFilePath(Content.Temp, ".mp3");
        try {
            mRecorder.setMyRecAudioFile(FileUtils.getFileByPath(musicPath));
            if (mRecorder.startRecorder()) {
                hasRecord = true;
                startTime();
            } else {
                ToastUtils.showShort(R.string.audio_fail_tips);
            }
        } catch (Exception e) {
            ToastUtils.showShort(R.string.audio_fail_tips2);
            e.printStackTrace();
        }
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopTime();
        FileUtils.deleteFilesInDir(PathUtils.getFilesPathExternalFirst() + Content.Temp);
    }
}